import {
  GraphQLObjectType, GraphQLID
} from 'graphql';

import { attributeFields, resolver } from 'graphql-sequelize';

import {
  fromGlobalId,
  globalIdField,
  connectionArgs,
  connectionFromArray,
} from 'graphql-relay';

import { User, Company, Contract } from '../models';

import relayNode from '../relay';
import ContractType from "./ContractType";
import {connectionFromModel, connectionFromType} from "../connection";

const CompanyType = new GraphQLObjectType({
  name: "Company",
  fields: () => Object.assign(
    {},
    attributeFields(Company, {
      exclude: [],
      globalId: true,
      allowNull: true,
    }),
    {
      contract: {
        type: ContractType,
        args: {
          id: {
            type: GraphQLID,
          },
        },
        resolve: async(user, { id }) => await Contract.findById(parseInt(fromGlobalId(id).id, 10))
      },
      contracts: {
        type: connectionFromType('contracts', ContractType).connection,
        args: {
          ...connectionArgs,
        },
        resolve: async (company, { ...args }) => {
          return connectionFromModel(Contract, {
            where: {
              company_id: company.id
            },
          }, args);
        }
      }
    },
  ),
  interfaces: [relayNode.nodeInterface],
});

export default CompanyType;
